using System;
using System.Data;
using System.Text;

using Tino.Core.Data;

namespace Tino.Core
{
    public class TagElement : ISqliteTable
    {
        public TagElement() { }

        public DataTable GetTags()
        {
            string SQL = "SELECT ID, Name FROM TagElement ORDER BY Name;";
            return SqliteAdapter.Get().Execute(SQL);
        }

        /// <summary>
        /// Ensure that the tag name is correctly formatted
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string Parse(string Input)
        {
            return Input.Trim().ToLower();
        }
        
        public int AddTag(string Name)
        {
            SqliteAdapter sqliteAdapter = new SqliteAdapter(Context.Current.ConnectionString);
            Name = TagElement.Parse(Name);
            
            // Make sure a tag with that name does not exist
            string SQL = "SELECT ID FROM TagElement WHERE Name = @Name;";
            DataTable dt = sqliteAdapter.Execute(SQL, "@Name", Name);
            if (dt.Rows.Count > 0)
                throw new ArgumentException(string.Format("Tag {0} already exists.", Name));

            SQL = "INSERT INTO TagElement (Name) VALUES (@Name);";
            SqliteAdapter.Get().ExecuteNonQuery(SQL, "@Name", Name);

            return Convert.ToInt32(SqliteAdapter.Get().ExecuteScalar("SELECT MAX(ID) FROM TagElement"));
        }

        public void DeleteTag(int TagID)
        {
            string SQL = "DELETE FROM TagElement WHERE ID = @ID;";
            SqliteAdapter.Get().ExecuteNonQuery(SQL, "@ID", TagID);

            // Then delete relation ...
            SQL = "DELETE FROM TaggedEntry WHERE TagID = @TagID;";
            SqliteAdapter.Get().ExecuteNonQuery(SQL, "@TagID", TagID);
        } 

        #region ISqliteTable Members

        public void CreateTable()
        {
            StringBuilder sb = new StringBuilder("CREATE TABLE [TagElement] ( ");
            sb.Append("ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,");
            sb.Append("Name VARCHAR NOT NULL )");

            SqliteAdapter.Get().ExecuteNonQuery(sb.ToString());
        }

        #endregion
    }
}
